package com.sky.task;

import com.sky.entity.Orders;
import com.sky.entity.RedisData;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 定时任务类，处理订单状态
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    @Resource(name = "orderRedisTemplate")
    private RedisTemplate<String, Object> orderRedisTemplate;
    /**
     * 处理超时订单
     */
    @Scheduled(cron = "0 * * * * ?")//每1分钟触发一次
    public void processTimeoutOrder(){
        log.info("定时处理超时订单：{}", LocalDateTime.now());

        String KEY="cacheovertime:order:";

        // 获取所有匹配的键
        Set<String> keys = orderRedisTemplate.keys(KEY + "*");
        if(keys != null && !keys.isEmpty()){
            for (String key : keys) {

                RedisData redisData = (RedisData) orderRedisTemplate.opsForValue().get(key);

                // 获取当前时间并减去15分钟
                LocalDateTime nowMinus15Minutes = LocalDateTime.now().minusMinutes(15);

                //判断是否超时
                if(nowMinus15Minutes.isAfter(redisData.getExpireTime())){

                    //该订单已超时
                    Orders order = new Orders();
                    order = (Orders) redisData.getData();

                    //1。修改数据库订单状态为已取消，并给出订单取消原因，取消时间
                    order.setStatus(Orders.CANCELLED);
                    order.setCancelReason("订单超时，自动取消");
                    order.setCancelTime(LocalDateTime.now());
                    orderMapper.update(order);

                    //2.删除该订单超时缓存
                    orderRedisTemplate.delete(KEY + order.getNumber());
                    log.info("删除订单超时缓存：{}", order.getNumber());
                }
            }
        }
    }

    @Scheduled(cron ="0 0 1 * * ?")//每天凌晨1点触发一次
    public void processDeliveryOrder(){
        log.info("定时处理处于派送中的订单：{}", LocalDateTime.now());
        LocalDateTime time=LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList=orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS,LocalDateTime.now());

        if(ordersList!=null && ordersList.size()>0){
            for(Orders order:ordersList){
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            }
        }
    }
}
